import MySQLdb
import string
import logging
from tools import config

logging.basicConfig(level=logging.DEBUG,format = "%(created)-15s %(msecs)d %(levelname)8s %(thread)d %(name)s %(message)s")
log = logging.getLogger(__name__)

class DBConn :
	
	def __init__ (self) :
		log.debug("__init__")
		"""initial stuff, connecting to database"""
		self.dbhost = config.getDBHost ()
		self.dbuser = config.getDBUser ()
		self.dbpass = config.getDBPass ()
		self.dbname = "pyhmon"
		self.db = MySQLdb.connect (host = self.dbhost, user = self.dbuser, passwd = self.dbpass, db=self.dbname)
		self.cursor=self.db.cursor()

	def query (self, tablename, nodename, start, end) :
		columns = "value0"
		for i in range(1,config.getValueNum(tablename)) :
			columns += ",value" + str(i)
		q = 'self.cursor.execute("SELECT time,' + columns + ' FROM ' + tablename
		q += " WHERE node='" + nodename + "' AND time>" + str(start)
		q += ' AND time<' + str(end) + ' ORDER BY time")'
		eval(q)
		return list(self.cursor.fetchall())
